import BaseSprite from "./Base/BaseSprite";
import BaseView from "./Base/BaseView";
import { EBundleType, EResType } from "./Common/Enum";
import EventID from "./Common/EventID";
import { GlobalData } from "./Common/GlobalData";
import { TalkModule } from "./Common/TalkModule";
import TaskModule from "./Common/TaskModule";
import { IMessage } from "./Interface/IMessage";
import { AdManager } from "./naodong/ads/AdManager";
import { ResManager1 } from "./naodong/manager/ResManager1";
import AppService from "./Service/AppService";
import AudioManager, { EMusicType } from "./Util/AudioManager";
import GameUtil from "./Util/GameUtil";
import { LoadUtil } from "./Util/LoadUtil";
import StorageUtil from "./Util/StorageUtil";
import { ItemToast } from "./View/Item/ItemToast";

export enum ELayerType {
    LayerLoad = "LayerLoad",
    LayerStory1 = "LayerStory1",
    LayerStory2 = "LayerStory2",
    LayerGame = "LayerGame",
}

export interface IGuideInfo {
    width: number;
    height: number;
    pos: cc.Vec2;
}

const { ccclass, property } = cc._decorator;

@ccclass
export class SceneGame extends BaseSprite implements IMessage {
    public static instance: SceneGame = null;

    @property({ type: cc.Prefab, tooltip: "提示" })
    private itemToast: cc.Prefab = null;

    @property({ type: cc.Node, tooltip: "根节点" })
    private rootNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "层节点" })
    private layerNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "弹窗节点" })
    private viewNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "弹窗层UI" })
    private viewUI: cc.Node = null;
    @property({ type: cc.Node, tooltip: "游戏层UI" })
    private gameUI: cc.Node = null;
    @property({ type: cc.Node, tooltip: "提示节点" })
    private toastNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "遮挡节点" })
    private topMaskNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "教学引导" })
    private guideUI: cc.Node = null;
    @property({ type: cc.Node, tooltip: "loading加载页" })
    private loadingUI: cc.Node = null;

    @property({ type: cc.Node, tooltip: "气泡" })
    public bubble: cc.Node = null;

    @property({ type: [cc.Node], tooltip: "资源节点" })
    private resNode: cc.Node[] = [];

    // private gameData: IGameData = null;
    private showUI: cc.Node = null;

    private layerMap: Map<string, { node: cc.Node, bundle: EBundleType }> = new Map();
    private popViewMap: Map<string, BaseView> = new Map();

    recvMsg(cmd: number, data: any) {
        switch (cmd) {
            case EventID.REFRESH_TOP_BAR:
                {
                    this.refreshTopBar(data?.type, data?.value);
                }
                break;
            // case EventID.EXIT_NAODONG:
            //     {
            //         switch (GlobalData.gameView) {
            //             case EGameType.Home:
            //                 AudioManager.instance.playMusic(EMusicType.HomeBgm, 0.3);
            //                 break;
            //             case EGameType.Town:
            //                 AudioManager.instance.playMusic(EMusicType.TownBgm);
            //                 break;
            //         }
            //     }
            //     break;
            case EventID.HIDE_VIEW_CLOSE: // 不显示弹窗层上方资源条或按钮
                {
                    switch(data.hide) {
                        case 'back':
                            setTimeout(() => {
                                const btnBack = cc.find("btnBack", this.viewUI);
                                btnBack.active = false;
                            }, 350);
                            break;
                        case 'top':
                            setTimeout(() => {
                                this.viewUI.x = -2500;
                            }, 350);
                            break;
                    }
                }
                break;
        }
    }

    protected onLoad() {
        super.onLoad();
        this.addMessage(EventID.REFRESH_TOP_BAR, this);
        // this.addMessage(EventID.EXIT_NAODONG, this);
        this.addMessage(EventID.HIDE_VIEW_CLOSE, this);

        SceneGame.instance = this;
        // this.gameData = StorageUtil.instance.getGameData();

        window["local"] = false;
        window["selectGame"] = "NaoDongTianHuaBan";
        ResManager1.ins.init();
        AdManager.initAds();

        this.gameUI.active = false;
        this.viewUI.active = false;

        this.adaptation();
        this.refreshTopBar();

        this.showLayer(ELayerType.LayerLoad);
    }

    protected start() { }

    protected onEnable() {
        cc.game.on(cc.game.EVENT_SHOW, this.onGameShowHandler, this);
        cc.game.on(cc.game.EVENT_HIDE, this.onGameHideHandler, this);
    }

    protected onDisable() {
        cc.game.off(cc.game.EVENT_SHOW, this.onGameShowHandler, this);
        cc.game.off(cc.game.EVENT_HIDE, this.onGameHideHandler, this);
    }

    private onGameShowHandler() {
        console.log("BaseScene.onChangeToGame()===>游戏进入前台~");
    }

    private onGameHideHandler() {
        console.log("BaseScene.onChangeToBack()===>游戏进入后台~");
        StorageUtil.instance.save();
    }

    private adaptation() {
        const size = cc.view.getVisibleSize();
        GlobalData.stage_width = size.width;
        GlobalData.stage_height = size.height;
        console.log("SceneGame.stageSize()===>屏幕尺寸:", GlobalData.stage_width, GlobalData.stage_height);
        console.log("ScemeGame.adaptation()===>缩放比例:", this.rootNode.scale);
        console.log("ScemeGame.adaptation()===>宽:", size.width * this.rootNode.scale);
        console.log("ScemeGame.adaptation()===>高:", size.height);
    }

    public getRootScale() {
        return this.rootNode.scale;
    }

    public getToastNode() {
        return this.toastNode;
    }

    public showGuideUI(node: cc.Node, scale: number = 1.2) {
        this.guideUI.active = true;
        const pos = GameUtil.localConvertWorldPointAR(node);
        const x = (pos.x - GlobalData.stage_width / 2) / this.rootNode.scale;
        const y = (pos.y - GlobalData.stage_height / 2) / this.rootNode.scale;
        const circle = cc.find('circle', this.guideUI);
        const mask = cc.find("mask", circle);
        const hand = cc.find("hand", this.guideUI);
        hand.active = false;
        mask.setPosition(cc.v2(-x, -y));

        // 高亮
        SceneGame.instance.showTopMask();
        const size = Math.max(node.width, node.height);
        circle.stopAllActions();
        circle.setPosition(cc.v2(x, y));
        circle.stopAllActions();
        cc.tween(circle).to(0, { width: 1000, height: 1000 }).to(0.2, { width: size * scale, height: size * scale }).call(() => {
            SceneGame.instance.hideTopMask();
            hand.active = true;
            hand.setPosition(cc.v2(circle.x + 105, circle.y - 85));
        }).start();
    }

    public hideGuideUI() {
        this.guideUI.active = false;
    }

    public getGuideUI() {
        return this.guideUI;
    }


    private refreshTopBar(resType?: EResType, value: number = 0) {
        this.resNode.forEach((o) => {
            const gameData = StorageUtil.instance.getGameData();
            const labMoney = cc.find("money/lab", o).getComponent(cc.Label);
            const labIq = cc.find("iq/lab", o).getComponent(cc.Label);
            let callback = () => {
                labMoney.string = GameUtil.changeUnit(gameData.money, 2);
                labIq.string = GameUtil.changeUnit(gameData.brain, 2);
            }
            if (resType >= 0 && value > 0) {
                const lab = resType === EResType.Money ? labMoney : labIq;
                GameUtil.instance.moveWordsAnimation(lab, value, callback);
            } else {
                callback && callback();
                callback = null;
            }
        });
    }

    public getFlyResData() {
        const money = cc.find("money", this.showUI);
        const ingot = cc.find("iq", this.showUI);
        return { flyNode: this.toastNode, money: money, ingot: ingot };
    }

    public showTopUI() {
        // this.gameUI.active = false;
        // this.viewUI.active = false;

        this.hideTopUI();
        const talkData = StorageUtil.instance.getTalkData();
        if (talkData.id > TalkModule.STORY) {
            if (this.popViewMap.size > 0) {
                const btnBack = cc.find("btnBack", this.viewUI);
                btnBack.active = true;
                this.viewUI.active = true;
                this.viewUI.x = 0;
                this.showUI = this.viewUI;
            } else {
                this.gameUI.active = true;
                this.gameUI.x = 0;
                this.showUI = this.gameUI;
            }
        }
    }

    public hideTopUI() {
        this.gameUI.x = -2500;
        this.viewUI.x = -2500;
    }

    public showTopMask() {
        this.topMaskNode.active = true;
        // console.log("SceneGame.showTopMask()===>打开全屏遮罩~");
    }

    public hideTopMask() {
        this.topMaskNode.active = false;
        // console.log("SceneGame.hideTopMask()===>关闭全屏遮罩~");
    }

    public showLoadingUI() {
        this.loadingUI.active = true;
    }

    public hideLoadingUI() {
        this.loadingUI.active = false;
    }


    /** 黑屏转场动画 */
    public changeLayerAnim(callback?: Function) {
        this.showTopMask();
        this.topMaskNode.stopAllActions();
        cc.tween(this.topMaskNode).sequence(
            cc.fadeIn(0.5),
            cc.fadeOut(0),
            cc.callFunc(() => {
                this.hideTopMask();
                callback && callback();
            }),
        ).start();
    }

    public getMaskActive() {
        return this.topMaskNode.active;
    }

    public getViewNode() {
        return this.viewNode;
    }

    public showToast(pos: cc.Vec2, toast: string, isRt: boolean = false) {
        const node = cc.instantiate(this.itemToast);
        node.parent = this.toastNode;
        node.setPosition(pos);
        node.getComponent(ItemToast).setLabel(toast, isRt);
        cc.tween(node).sequence(
            cc.moveTo(1, cc.v2(pos.x, pos.y + 250)),
            cc.delayTime(0.8),
            cc.callFunc(() => {
                node.removeFromParent();
            }),
        ).start();
    }

    public showLayer(name: ELayerType) {
        const viewData = AppService.instance.getRegistView(name);
        if (viewData) {
            this.clearLayer();
            const bundle = viewData.bundle;
            const url = `prefab/${viewData.name}`;
            LoadUtil.instance.loadRes(bundle, url, cc.Prefab, (err, res) => {
                if (!err && res) {
                    const node = cc.instantiate(res);
                    node.zIndex = viewData.zIndex;
                    node.parent = this.layerNode;
                    this.layerMap.set(name, { node: node, bundle: bundle });
                }
            });
        } else {
            console.log(`SceneGame.showLayer()===>${name}: 未注册页面~`);
        }
    }

    public showPopView(name: string, data?: any) {
        if (this.popViewMap.get(name)) {
            return;
        }

        const viewData = AppService.instance.getRegistView(name);
        if (viewData) {
            const bundle = viewData.bundle;
            const name = viewData.name;
            const zIndex = viewData.zIndex;
            let url = `prefab/panel/${name}`;
            LoadUtil.instance.loadRes(bundle, url, cc.Prefab, (err, res: cc.Prefab) => {
                if (!err && res) {
                    const node = cc.instantiate(res);
                    const comp = node.getComponent(`${name}`)
                    comp?.prepare(data);
                    node.parent = this.viewNode;
                    node.zIndex = zIndex;
                    this.popViewMap.set(name, comp);

                    console.log(this.popViewMap);
                }
            });

            // 收回任务提示
            TaskModule.instance.hideTask();
        }
    }

    public getViewMask() {
        const mask = cc.find('mask', this.viewNode);
        return mask;
    }

    private clear(name: ELayerType) {
        const data = this.layerMap.get(name);
        if (data) {
            // LoadUtil.instance.removeBundle(data.bundle);
            this.layerNode.removeChild(data.node);
            data.node.destroy();
            this.layerMap.delete(name);
        }

        // console.log(cc.assetManager.assets, cc.assetManager.assets.count);
    }

    private clearLayer() {
        for (let entries = this.layerMap.entries(), entry = entries.next(); !entry.done; entry = entries.next()) {
            const [key, value] = entry.value;
            this.clear(key);
        }
    }

    public removePopView(temp: string | cc.Node) {
        if (temp instanceof cc.Node) {
            temp = temp.name;
        }
        const data = this.popViewMap.get(temp);
        if (data) {
            if (!data.isHasChild) {
                data.onCloseClicked();
                this.popViewMap.delete(temp);
            } else {
                data.onCloseChild();
            }
        } else {
            console.log(`SceneGame.removePopView()===>弹窗${temp}不存在~`);
        }
    }

    public removeLastView() {
        const index = this.popViewMap.size - 1;
        const end = Array.from(this.popViewMap)[index];
        if (end) {
            this.removePopView(end[0]);
        }
    }

    public removeAllPopView() {
        for (let entries = this.popViewMap.entries(), entry = entries.next(); !entry.done; entry = entries.next()) {
            const [key, value] = entry.value;
            this.removePopView(key);
        }
    }

    public getPopViewSize() {
        return this.popViewMap.size;
    }

    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case 'btnBack':
                {
                    this.removeLastView();
                }
                break;
            case 'btnClean':
                {
                    StorageUtil.instance.clear();
                    cc.director.loadScene(cc.director.getScene().name);
                }
                break;
        }
    }
}